<template>
  <div class="flowable-definition">
    <!-- 通用功能区 -->
    <el-card shadow="never" class="controls-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" class="demo-form-inline">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入流程名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
      <el-form-item label="开始时间" prop="deployTime">
        <el-date-picker clearable 
                        v-model="queryParams.deployTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleLoadXml"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:deployment:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    </el-card>
    <!-- 主内容区 -->
    <!-- <el-card shadow="never" class="main-content-card"> -->
      <el-alert title="流程设计说明" type="success" class="flow-design-explanation-alert">
      <template #title>
        <p>流程设计说明:</p>
        <div>1、XML文件中的流程定义id属性用作流程定义的key参数。</div>
        <div>2、XML文件中的流程定义name属性用作流程定义的name参数。如果未给定name属性，会使用id作为name。</div>
        <div>3、当每个唯一key的流程第一次部署时，指定版本为1。对其后所有使用相同key的流程定义，部署时版本会在该key当前已部署的最高版本号基础上加1。key参数用于区分流程定义。</div>
        <div>4、id参数设置为{processDefinitionKey}:{processDefinitionVersion}:{generated-id}，其中generated-id是一个唯一数字，用以保证在集群环境下，流程定义缓存中，流程id的唯一性。</div>
      </template>
      </el-alert>
      <el-table v-loading="loading" fit :data="definitionList" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column label="流程编号" align="center" prop="deploymentId" :show-overflow-tooltip="true"/>
        <el-table-column label="流程标识" align="center" prop="flowKey" :show-overflow-tooltip="true" />
        <el-table-column label="流程分类" align="center" prop="category" />
        <el-table-column label="流程名称" align="center" width="150" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-button link @click="handleReadImage(scope.row.deploymentId)">
              <span>{{ scope.row.name }}</span>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="业务表单" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <el-button v-if="scope.row.formId" link @click="handleForm(scope.row.formId)">
              <span>{{ scope.row.formName }}</span>
            </el-button>
            <label v-else>暂无表单</label>
          </template>
        </el-table-column>
        <el-table-column label="流程版本" align="center" width="100">
          <template #default="scope">
            <el-tag size="default" >v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.suspensionState === 1">激活</el-tag>
            <el-tag type="warning" v-if="scope.row.suspensionState === 2">挂起</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="部署时间" align="center" prop="deploymentTime" width="180"/>
        <el-table-column label="操作" align="center" width="350" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button @click="handleLoadXml(scope.row)" :icon="Edit" link>设计</el-button>
            <el-button @click="handleAddForm(scope.row)" :icon="Promotion" link v-if="scope.row.formId == null">配置主表单</el-button>
            <el-button @click="handleUpdateSuspensionState(scope.row)" :icon="VideoPause" link v-if="scope.row.suspensionState === 1">挂起</el-button>
            <el-button @click="handleUpdateSuspensionState(scope.row)" :icon="VideoPlay" link v-if="scope.row.suspensionState === 2">激活</el-button>
            <el-button @click="handleDelete(scope.row)" :icon="Delete" link v-hasPermi="['system:deployment:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    <!-- </el-card> -->

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改流程定义对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="看看" prop="name">
          <el-input v-model="form.name" placeholder="请输入看看" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- bpmn20.xml导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xml"
        :headers="upload.headers"
        :action="upload.url + '?name=' + upload.name+'&category='+ upload.category"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            流程名称：<el-input v-model="upload.name"/>
            流程分类：
            <div>
              <!--          <el-input v-model="upload.category"/>-->
              <el-select v-model="upload.category" placeholder="请选择流程分类">
                <el-option
                  v-for="dict in dict.type.sys_process_category"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="el-upload__tip" style="color:red">提示：仅允许导入"bpmn20.xml"格式文件！</div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 流程图 -->
    <el-dialog :title="readImage.title" v-model="readImage.open" width="70%" append-to-body>
      <!-- <el-image :src="readImage.src"></el-image> -->
      <bpmn-viewer :flowData="flowData"/>
    </el-dialog>

    <!--表单配置详情-->
    <el-dialog :title="formTitle" v-model="formConfOpen" width="50%" append-to-body>
      <div class="test-form">
        <v-form-render :form-data="formData" ref="vFormRef"/>
      </div>
    </el-dialog>

    <!--挂载表单-->
    <el-dialog :title="formDeployTitle" v-model="formDeployOpen" width="60%" append-to-body>
      <el-row :gutter="24">
        <el-col :span="10" :xs="24">
          <el-table
            ref="singleTable"
            :data="formList"
            border
            highlight-current-row
            @current-change="handleCurrentChange"
            style="width: 100%">
            <el-table-column label="表单编号" align="center" prop="formId" />
            <el-table-column label="表单名称" align="center" prop="formName" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" @click="handleSelectedForm(scope.row)"
                >选择
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="14" :xs="24">
          <div class="test-form">
            <v-form-render :form-data="formData" ref="vFormRef2"/>
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="formDeployOpen = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!--流程设计器-->
    <!-- <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="90%"
      top="2vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      append-to-body
      draggable
    >
      <workflow-design
        v-if="dialogVisible"
        ref="workflowDesign"
        :modeler="true"
        :key-modeler="key"
        :process="processObj"
        @closeDiagram="closeDiagram"
        @saveProcess="saveProcess"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup>
import { getForm, listForm, addDeployForm } from "@/api/flowable/form";
import { listDefinition, updateState, readXml, saveXml, delDeployment, flowXmlAndNode } from "@/api/flowable/definition";
// import WorkflowDesign from "@/components/Process/workflow-design";
// import VFormRender from "@/components/VForm/VFormRender";
import BpmnViewer from '@/components/Process/viewer';
import { getToken } from "@/utils/auth";
import { getCurrentInstance, ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { Search, Refresh, Plus, Delete, Edit, Promotion, VideoPause, VideoPlay } from '@element-plus/icons-vue';
import { useDict } from '@/utils/dict';
import { ElMessage, ElMessageBox } from 'element-plus';

const { proxy } = getCurrentInstance();
const router = useRouter();
const dict = useDict('sys_process_category');

// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 流程定义表格数据
const definitionList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 表单参数
const form = reactive({});
// 表单校验
const rules = reactive({});
// 表单数据
const formData = reactive({});
const formList = ref([]);
const vFormRef = ref(null);
const vFormRef2 = ref(null);
const formTitle = ref(null);
const formConfOpen = ref(false);
const formDeployTitle = ref('配置表单');
const formDeployOpen = ref(false);
const currentRowData = ref(null);
const flowData = ref({});

const formTotal = ref(0);

const formDeployParam = reactive({
  formId:null,
  deployId: null
});

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  category: null,
  deployTime: null
});

const formQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 上传参数
const upload = reactive({
  open: false,
  title: "流程导入",
  url: import.meta.env.VITE_APP_BASE_API + "/flowable/definition/import",
  name: "",
  category: "",
  headers: { Authorization: "Bearer " + getToken() },
  isUploading: false
});

const readImage = reactive({
  title: '流程图',
  open: false,
  src: ""
});

// 流程设计器相关 - 这些与弹窗设计器相关，如果统一跳转到新页面，则不再由此处直接控制
// const dialogVisible = ref(false);
// const dialogTitle = ref('流程设计器');
// const key = ref(new Date().getTime()); // 用于刷新设计器，新页面会有自己的逻辑
// const processObj = reactive({
//   processXml: '',
//   processName: '',
//   category: '',
//   processId: ''
// });

/** 查询流程定义列表 */
function getList() {
  loading.value = true;
  listDefinition(queryParams).then(response => {
    definitionList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    name: null,
    category: null,
    key: null,
    tenantId: null,
    deployTime: null,
    derivedFrom: null,
    derivedFromRoot: null,
    parentDeploymentId: null,
    engineVersion: null
  };
  resetForm("form");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryForm");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加流程定义";
}

/** 用户导入 */
function handleImport() {
  upload.title = "流程导入";
  upload.open = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value[0];
  getDeployment(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改流程定义";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["form"].validate(valid => {
    if (valid) {
      if (form.id != null) {
        updateDeployment(form).then(response => {
          ElMessage.success(
            "修改成功",
            3
          );
          open.value = false;
          getList();
        });
      } else {
        addDeployment(form).then(response => {
          ElMessage.success(
            "新增成功",
            3
          );
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.deploymentId || ids.value;
  ElMessageBox.confirm('是否确认删除流程定义编号为"' + ids + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(function() {
      return delDeployment(ids);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    })
    .catch(() => {});
}

/** 流程挂起/激活 */
function handleUpdateSuspensionState(row) {
  let state = 1;
  if (row.suspensionState === 1) {
    state = 2;
  }

  ElMessageBox.confirm(`确认要${row.suspensionState == 1 ? "挂起" : "激活"}"${row.name}"流程吗?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(function() {
      return updateState({ deployId: row.deploymentId, state: state });
    })
    .then(() => {
      ElMessage.success(`${row.suspensionState == 1 ? "挂起" : "激活"}成功`);
      getList();
    })
    .catch(() => {});
}

/** 查看流程图 */
function handleReadImage(deployId) {
  readImage.title = '流程图';
  readImage.open = true;
  flowXmlAndNode({deployId: deployId}).then(res => {
    // console.log("BPMN XML Data:", res.data); // 打印返回的数据
    flowData.value = res.data;
  }).catch(error => {
    console.error("Error fetching flow data:", error);
    ElMessage.error("加载流程图失败，请检查流程定义ID是否正确");
  });
}

/** 导入结果 */
function handleFileSuccess(response) {
  upload.open = false;
  upload.isUploading = false;
  getList();
  ElMessage.success(response.msg);
}

/** 导入结果 */
function handleFileError() {
  upload.open = false;
  upload.isUploading = false;
  ElMessage.error("导入失败！");
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs.upload.submit();
}

/** 上传中处理 */
function handleFileUploadProgress() {
  upload.isUploading = true;
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.deploymentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/* 流程表单查看 */
function handleForm(formId){
  getForm(formId).then(res =>{
    formTitle.value = "表单详情";
    formConfOpen.value = true;
    nextTick(() => {
      // 回显数据
      proxy.$refs.vFormRef.setFormJson(JSON.parse(res.data.formContent))
      nextTick(() => {
        // 表单禁用
        proxy.$refs.vFormRef.disableForm();
      })
    })
  })
}

/** 流程表单挂载 */
function handleAddForm(row) {
  formDeployParam.deployId = row.deploymentId;
  listForm(formQueryParams).then(response => {
    // console.log(response);
    formList.value = response.rows;
    formTotal.value = response.total;
    formDeployOpen.value = true;
  });
}

/** 当前行变动 */
function handleCurrentChange(currentRow) {
  // this.$refs.singleTable.setCurrentRow(currentRow);
  currentRowData.value = currentRow;
  // 回显表单
  // console.log("Current Row Data --->:", currentRowData.value);
  vFormRef2.value.setFormJson(JSON.parse(currentRowData.value.formContent));
}

/** 选择表单 */
function handleSelectedForm(row) {
  formDeployParam.formId = row.formId;
  addDeployForm(formDeployParam).then(res =>{
    proxy.$modal.msgSuccess(res.msg);
    formDeployOpen.value = false;
    getList();
  })
}

/**
 * 流程设计器 / 新增(跳转到模型设计页面)
 * @param row 流程数据，用于设计现有流程
 */
function handleLoadXml(row) {
  const query = {};
  if (row && row.deploymentId) {
    query.deployId = row.deploymentId;
  }
  router.push({ path: '/flowable/definition/model', query: query });
}

/**
 * 关闭流程设计器对话框 - 不再需要，因为设计在单独页面
 */
// function closeDiagram() {
//   dialogVisible.value = false;
// }

/**
 * 保存流程 - 不再需要，因为保存在单独页面完成
 */
// function saveProcess(data) {
//   saveXml(data).then(response => {
//     ElMessage.success('保存流程成功');
//     // 关闭流程设计器对话框
//     // closeDiagram(); // closeDiagram is already commented out
//     // 重新查询流程列表
//     getList();
//   });
// }

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.flowable-definition {

  .controls-card {
    margin-bottom: 15px;
  }

  .main-content-card {
    height: 70vh; /* 设置容器固定高度 */
    display: flex;
    flex-direction: column;
    :deep(.el-card__body) {
      flex-grow: 1; /* 使卡片主体填充可用空间 */
      overflow-y: auto; /* 当内容溢出时，在卡片主体上显示垂直滚动条 */
      /* padding: 20px; /* 保留 Element Plus 默认的 el-card__body padding, 可根据需要调整 */
      /* 如果el-card__body有内边距，子元素height:100%可能会导致内容区域略小或需要box-sizing */
    }
  }
    
  .mb8 {
    margin-bottom: 8px;
  }
  .test-form {
    margin: 15px auto;
    width: 600px;
    padding: 15px;
    }

  .demo-form-inline {
    display: flex;
    flex-flow: row wrap;
    align-items: center;
    
    /* 设置输入框和选择器的宽度 */
    :deep(.el-input) {
      --el-input-width: 240px;
    }
    
    :deep(.el-select) {
      --el-select-width: 240px;
    }
    :deep(.el-date-editor) {
      --el-date-editor-width: 240px;
    } 
    
    /* 添加响应式设计，在小屏幕上垂直排列 */
    @media (max-width: 768px) {
      flex-direction: column;
      align-items: flex-start;
      
      .el-form-item {
        margin-right: 0;
        width: 100%;
      }
    }
  }
}
</style>
